package com.chen.androidstudy.activity.recycle;

import android.util.Log;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;

/**
 * @Author: CHong
 * @CreateDate: 2024/9/4 0004
 * @Description:
 */
public class RvCountDownHelper {

    private List<Index> countDownPositions = new ArrayList<>();
    private RecyclerView.Adapter rvAdapter;
    private RecyclerView recyclerView;

    private Disposable countDownTask;

    private OnTimeCollectListener mListener;

    public RvCountDownHelper(RecyclerView.Adapter rvAdapter, RecyclerView recyclerView) {
        this.recyclerView = recyclerView;
        this.rvAdapter = rvAdapter;
        rvAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
            @Override
            public void onChanged() {
                removeAllPosition();
                super.onChanged();
                Log.d("AdapterDataObserver", "onChanged");
            }

            @Override
            public void onItemRangeChanged(int positionStart, int itemCount) {
                super.onItemRangeChanged(positionStart, itemCount);
                Log.d("AdapterDataObserver", "onItemRangeChanged");
            }

            @Override
            public void onItemRangeChanged(int positionStart, int itemCount, @Nullable Object payload) {
                super.onItemRangeChanged(positionStart, itemCount, payload);
                Log.d("AdapterDataObserver", "onItemRangeChanged");
            }

            @Override
            public void onItemRangeInserted(int positionStart, int itemCount) {
                for (Index countDownPosition : countDownPositions) {
                    if (countDownPosition.index >= positionStart) {
                        countDownPosition.index += itemCount;
                    }
                }
                super.onItemRangeInserted(positionStart, itemCount);
                Log.d("AdapterDataObserver", "onItemRangeInserted");
            }

            @Override
            public void onItemRangeRemoved(int positionStart, int itemCount) {
                for (int i = countDownPositions.size() - 1; i >= 0; i--) {
                    Index temp = countDownPositions.get(i);
                    if (temp.index >= positionStart + itemCount) {
                        temp.index = temp.index - itemCount;
                    } else if (temp.index >= positionStart) {
                        removeCountDownPosition(temp.index);
                    }
                }
                super.onItemRangeRemoved(positionStart, itemCount);
                Log.d("AdapterDataObserver", "onItemRangeRemoved");
            }

            @Override
            public void onItemRangeMoved(int fromPosition, int toPosition, int itemCount) {

                Log.d("ItemMove", "frompos =" + fromPosition + " toPos =" + toPosition + " itemCount= " + itemCount);

                for (Index countDownPosition : countDownPositions) {
                    if (countDownPosition.index == fromPosition) {
                        countDownPosition.index = toPosition;
                    }else if (countDownPosition.index == toPosition) {
                        countDownPosition.index = fromPosition;
                    }
                }

                super.onItemRangeMoved(fromPosition, toPosition, itemCount);
                Log.d("AdapterDataObserver", "onItemRangeMoved");
            }
        });
    }

    public void setOnTimeCollectListener(OnTimeCollectListener listener) {
        this.mListener = listener;
    }

    /**
     * 新增一个需要倒计时的item位置
     * @param pos
     */
    public void addPosition2CountDown(int pos) {
        Index addPos = new Index(pos);
        if (!countDownPositions.contains(addPos)) {
            Log.d("CountDown", "新增pos-" + pos);
            countDownPositions.add(addPos);
            startCountDown();
        }
    }

    /**
     * 移除一个需要定时更新的item
     * @param pos
     */
    public void removeCountDownPosition(int pos) {
        boolean remove = countDownPositions.remove(new Index(pos));
        Log.d("CountDown", "移除pos-" + pos + "result = " + remove);

    }

    /**
     * 移除所有需要定时更新的item
     */
    public void removeAllPosition() {
        countDownPositions.clear();
        Log.d("CountDown", "移除所有标记位置");
    }

    /**
     * 手动调用开始定时更新
     */
    public void startCountDown() {
        if (countDownTask == null || countDownTask.isDisposed()) {
            countDownTask = Observable.interval(0, 1000, TimeUnit.MILLISECONDS)
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(aLong -> {
                        Log.d("倒计时--", "cur aLong= " + aLong);

                        if (countDownTask.isDisposed()) {
                            return;
                        }

                        if (countDownPositions.isEmpty()) {
                            countDownTask.dispose();
                            return;
                        }

                        for (Index countDownPosition : countDownPositions) {
                            RecyclerView.LayoutManager lm = recyclerView.getLayoutManager();
                            if (lm != null) {
                                View itemView = recyclerView.getLayoutManager().findViewByPosition(countDownPosition.index);
                                if (itemView != null) {
                                    if (mListener != null) {
                                        RecyclerView.ViewHolder viewHolder = recyclerView.findViewHolderForPosition(countDownPosition.index);
                                        mListener.onTimeCollect(viewHolder, countDownPosition.index);
                                    } else {
                                        rvAdapter.notifyItemChanged(countDownPosition.index);
                                    }
                                }
                            }

                        }

                    }, throwable -> Log.e("倒计时异常", throwable.getMessage()));

        }
    }

    /**
     * 手动调用停止定时更新
     */
    public void stopCountDown() {
        if (countDownTask != null && !countDownTask.isDisposed()) {
            countDownTask.dispose();
        }
    }

    /**
     * 获取所有的item位置记录
     */
    public List<Index> getAllRecordPos() {
        return countDownPositions;
    }

    /**
     * 销毁
     */
    public void destroy() {
        stopCountDown();
        mListener = null;
        countDownTask = null;
        recyclerView = null;
        rvAdapter = null;
    }

    interface OnTimeCollectListener {
        void onTimeCollect(RecyclerView.ViewHolder vh,int pos);
    }

    static class Index {
        int index;

        public Index(int index) {
            this.index = index;
        }

        @Override
        public boolean equals(@Nullable Object obj) {
            if(!(obj instanceof Index)) {
                // instanceof 已经处理了obj = null的情况
                return false;
            }
            Index indObj = (Index) obj;
            // 地址相等
            if (this == indObj) {
                return true;
            }
            // 如果两个对象index相等
            return indObj.index == this.index;
        }

        @Override
        public int hashCode() {
            return 128 * index;
        }
    }
}